const md5 = require('md5')
const xml2js = require('xml2js')
const Parser = new xml2js.Parser()
const uuid = require('uuid/v4')
const randomChar = uuid().toString().replace(/-/g, '') //随机生成的字符串
const request = require('request')

/**
 * 对指定字符串进行md5加密
 * @param {String} str 
 */
// 1、判断用户付了多少钱
exports.checkOrder = async function (orderId) {
    return new Promise(async (resolve, reject) => {
        let config = {
            appid: 'wx24a21b47e8d32f78',
            mch_id: 1529114461,
            out_trade_no: orderId, //商户订单号
            nonce_str: randomChar,
            sign_type: 'MD5'
        }
        let arr = Object.keys(config).sort().map(item => {
            return `${item}=${config[item]}`;
        });
        // 这里拼接签名字符串的时候一定要注意: 商户的key是要单独拿出来拼在最后面的
        let str = arr.join('&') + '&key=f2ec4b1440f6f15e1a6a5dca0bb704b3';
        config.sign = getSign(str);
        try {
            // 调用微信统一下单接口拿到 prepay_id
            let res = await wechatPay(config);
            resolve(res)
        } catch (e) {
            reject(e)
        }
    })

    // request.get('https://api.mch.weixin.qq.com/pay/orderquery')
}
const getSign = (str) => {
    return md5(str).toUpperCase();
}
/**
 * 统一下单 prepay_url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
 * @param {Object} obj 调用统一下单的必须参数
 */
const wechatPay = (obj) => {
    let xml = json2xml(obj);
    //   console.log(xml)
    return new Promise((resolve, reject) => {
        // 这里用了reques库,不熟悉的同学可以看看相关文档 https://github.com/request/request
        // 总之就是向微信的统一下单接口提交一个xml
        request({
            method: 'POST',
            url: 'https://api.mch.weixin.qq.com/pay/orderquery',
            body: xml
        }, (err, res, body) => {
            if (err) {
                reject(err);
            } else {
                //如果成功即可得到微信返回参数
                // console.log(body);
                let obj = parseXml(body).xml;
                resolve(obj);
            }
        });
    });
}
/**
 * 转化xml用了xml2js库  
    https://github.com/Leonidas-from-XIV/node-xml2js
 * @param {Object} obj 
 */
const json2xml = (obj) => {
    let builder = new xml2js.Builder({
        headless: true,
        allowSurrogateChars: true,
        rootName: 'xml',
        cdata: true
    });
    var xml = builder.buildObject(obj);
    return xml;
}
const parseXml = (xml) => {
    let {
        parseString
    } = xml2js;
    let res;
    parseString(xml, {
        trim: true,
        explicitArray: false
    }, function (err, result) {
        res = result;
    });
    return res;
}